package com.zrx.govern.component.easyexcel.starter;


import com.zrx.govern.component.easyexcel.starter.aop.DownloadTemplateExcelReturnValueHandler;
import com.zrx.govern.component.easyexcel.starter.aop.ResponseExcelReturnValueHandler;
import com.zrx.govern.component.easyexcel.starter.config.ExcelConfigProperties;
import com.zrx.govern.component.easyexcel.starter.handler.SheetWriteHandler;
import com.zrx.govern.component.easyexcel.starter.processor.NameProcessor;
import com.zrx.govern.component.easyexcel.starter.processor.NameSpelExpressionProcessor;
import com.zrx.govern.component.easyexcel.starter.utils.FileZipUtil;
import com.zrx.govern.component.easyexcel.starter.utils.JsonParseUtil;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangxiaowei
 * <p>
 * 配置初始化
 */
@RequiredArgsConstructor
@Configuration
@EnableConfigurationProperties(ExcelConfigProperties.class)
public class ResponseExcelAutoConfiguration implements ApplicationContextAware, InitializingBean {
    private static ApplicationContext applicationContext;
    private final List<SheetWriteHandler> sheetWriteHandlerList;
    private final ExcelConfigProperties excelConfigProperties;


    @Bean
    @ConditionalOnMissingBean
    public NameProcessor nameProcessor() {
        return new NameSpelExpressionProcessor();
    }


    @Override
    public void afterPropertiesSet() {
        RequestMappingHandlerAdapter handlerAdapter = applicationContext.getBean(RequestMappingHandlerAdapter.class);
        List<HandlerMethodReturnValueHandler> returnValueHandlers = handlerAdapter.getReturnValueHandlers();

        List<HandlerMethodReturnValueHandler> newHandlers = new ArrayList<>();
        newHandlers.add(new ResponseExcelReturnValueHandler(sheetWriteHandlerList));
        newHandlers.add(new DownloadTemplateExcelReturnValueHandler(excelConfigProperties));
        assert returnValueHandlers != null;
        newHandlers.addAll(returnValueHandlers);
        handlerAdapter.setReturnValueHandlers(newHandlers);
    }

    @SneakyThrows
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ResponseExcelAutoConfiguration.applicationContext = applicationContext;
        /*1.初始化加载json配置文件*/
        JsonParseUtil.initExcelSettingJson(excelConfigProperties);
        /*2.设置excel文件默认路径*/
        //System.out.println(getJarPath());
        String excelPath = getExcelPath();
        //System.out.println(excelPath);
		File uploadDir = new File(excelPath);
		if (!uploadDir.exists()) {
			uploadDir.mkdirs();
		}
        //设置excel临时文件路径
        FileZipUtil.setExcelPath(excelPath);


    }

    @SneakyThrows
    private String getExcelPath() {
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.contains("win")) {
            //System.out.println("******当前操作系统为windows环境*********");
            Resource resource = new ClassPathResource(File.separator + excelConfigProperties.getTemplatePath());
            return resource.getFile().getAbsolutePath();
        } else {
            //System.out.println("******当前操作系统为linux环境*********");
            ApplicationHome h = new ApplicationHome(this.getClass());
            File jarF = h.getSource();
            String jarPath = jarF.getParentFile().getAbsolutePath();
            return jarPath + File.separator + excelConfigProperties.getTemplatePath();
        }
    }

    /**
     * 获取当前jar包路径
     *
     * @return
     */
    private String getJarPath() {
        ApplicationHome h = new ApplicationHome(JsonParseUtil.class);
        File jarF = h.getSource();
        return jarF.getParentFile().getAbsolutePath();
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}
